package com.jzz.eletuanbackend.service;

import com.jzz.eletuanbackend.mapper.UserMapper;
import com.jzz.eletuanbackend.util.Msg;
import com.jzz.eletuanbackend.util.TokenValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class AuthService {

    @Autowired
    private TokenValidator tokenValidator;

    @Autowired
    private UserMapper userMapper;


    /* ******************公共接口部分****************** */

    /**
     * 根据用户ID生成Token
     *
     * 只能在登录的时候远程调用这个方法
     *
     * @param userId 用户ID，第一个字符为[C/B/D]，用来表示顾客、商家和配送员
     * @return 有效的Token信息
     */
    public String generateToken(String userId) {
        return tokenValidator.getValidAccessToken(userId);
    }

    public Msg refreshToken(String oldToken) {
        String uid = tokenValidator.getTokenUId(oldToken);

        if (uid.equals("")) {
            return Msg.err(-1, "无效Token");
        } else {
            return Msg.ok("success", tokenValidator.getValidAccessToken(uid));
        }
    }

    public String getUserId(String token) {
        return tokenValidator.getTokenUId(token);
    }

    public Msg signIn(HttpServletRequest request, HttpServletResponse response, String phone, String password) {
        if (phone.length() < 2 || password.isEmpty()) {
            return Msg.err(-1, "手机号或密码错误");
        }
        String type = phone.substring(0, 1);
        String realPhone = phone.substring(1);

        switch (type) {
            case "C":
            case "B":
            case "D":
                Integer userId = userMapper.signIn(type, realPhone, password);
                if (userId == null) {
                    return Msg.err(-1, "手机号或密码错误");
                }
                String token = generateToken(type + userId);

                response.addHeader("Token", token);
                return Msg.ok("登录成功", info(token).getData());
            default:
                return Msg.err(-1, "错误的请求格式");
        }
    }

    public Msg signUpAsCustomer(String phone, String password, String displayName) {
        try {
            int result = userMapper.signUpAsCustomer(phone, displayName == null ? "u" + phone : displayName, password, "[]");
            if (result > 0) {
                return Msg.ok("注册成功");
            } else {
                return Msg.err(-1, "手机号已存在");
            }
        } catch (Exception e) {
            return Msg.err(-1, "手机号已存在");
        }
    }

    public Msg signUpAsDeliverer(String phone, String password, String name, String healthId) {
        try {
            int result = userMapper.signUpAsDeliverer(phone, name, healthId, password);
            if (result > 0) {
                return Msg.ok("注册成功");
            } else {
                return Msg.err(-1, "手机号已存在");
            }
        } catch (Exception e) {
            return Msg.err(-1, "手机号已存在");
        }
    }

    public Msg signUpAsBusiness(String phone, String password) {
        try {
            int result = userMapper.signUpAsBusiness(phone, password);
            if (result > 0) {
                return Msg.ok("注册成功");
            } else {
                return Msg.err(-1, "手机号已存在");
            }
        } catch (Exception e) {
            return Msg.err(-1, "手机号已存在");
        }
    }

    public Msg isValidToken(String token) {
        String uid = tokenValidator.getTokenUId(token);
        if (uid.equals("")) {
            return Msg.err(-1, "无效Token");
        } else {
            return Msg.ok("success");
        }
    }

    public Msg info(String token) {
        String uid = tokenValidator.getTokenUId(token);
        if (uid.equals("")) {
            return Msg.err(-1, "无效Token");
        } else {
            return Msg.ok("success", userMapper.get(uid.substring(0, 1), Long.parseLong(uid.substring(1))));
        }
    }
}
